package com.videoaggre.zcl.api

import com.videoaggre.zcl.common.ServiceConfig
import com.videoaggre.zcl.helper.mohsi.MOSHI
import com.videoaggre.zcl.utils.Logger
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

val SERVICE: ApiService
    get() = ApiHelper.apiService
val ENTERDESK_SERVICE: ScalarsApiService
    get() = ApiHelper.enterdeskApiService
val MEIZUO_SERVICE: ScalarsApiService
    get() = ApiHelper.meizuoApiService
val QIMAN_SERVICE: ScalarsApiService
    get() = ApiHelper.qimanApiService

object ApiHelper {
    const val ENTERDESK = "https://m.sj.enterdesk.com/"//车桌面
    const val MEIZUO = "http://www.win4000.com/"//美桌
    const val QIMAN = "http://m.qiman6.com/"//奇漫屋
    private const val TIME_OUT = 60L
    val apiService: ApiService by lazy { createRetrofit(TIME_OUT, ServiceConfig.getCurrentServiceConfig().apiUrl).create(ApiService::class.java) }
    val enterdeskApiService: ScalarsApiService by lazy { getScalarsService(ENTERDESK) }
    val meizuoApiService: ScalarsApiService by lazy { getScalarsService(MEIZUO) }
    val qimanApiService: ScalarsApiService by lazy { getScalarsService(QIMAN) }

    fun createService(timeout: Long) = createRetrofit(timeout, ServiceConfig.getCurrentServiceConfig().apiUrl).create(ApiService::class.java)

    private fun getScalarsService(baseUrl: String) = Retrofit.Builder()
        .client(getOkHttpClient(TIME_OUT))
        .addConverterFactory(ScalarsConverterFactory.create())
        .baseUrl(baseUrl)
        .build()
        .create(ScalarsApiService::class.java)
}

private fun createRetrofit(timeout: Long, url: String) = Retrofit.Builder()
    .client(getOkHttpClient(timeout))
    .addConverterFactory(MoshiConverterFactory.create(MOSHI))
    .baseUrl(url)
    .build()

private fun getOkHttpClient(timeout: Long): OkHttpClient {
    return OkHttpClient.Builder()
        .connectTimeout(timeout, TimeUnit.SECONDS)
        .writeTimeout(timeout, TimeUnit.SECONDS)
        .readTimeout(timeout, TimeUnit.SECONDS)
        //.addInterceptor(SignInterceptor())
        //.addNetworkInterceptor(getHttpLoggingInterceptor())
        .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
        .build()
}

private fun getHttpLoggingInterceptor(): HttpLoggingInterceptor {
    val level = HttpLoggingInterceptor.Level.BODY
    val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
        override fun log(message: String) {
//                if (BuildConfig.DEBUG) {
            Logger.e("Api请求==>$message")
//                }
        }
    })
    loggingInterceptor.setLevel(level)
    return loggingInterceptor
}